import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'

import router from './router'
import store from './store'

const AAA = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token

  console.log(token, '222token')

  // next()

  // 判断是否又token
  //    又token判断是否在登录页在进入首页

  //  没有token
  // 判断是否访问在白名单内，通过
  //  返回登录页

  if (token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      // 考虑到有token 每个页面大概都用到用户信息，所以在守卫获取用户存储token
      // 为了执行顺序，发送，获取，页面 用await解决
      // 有参数在发送请求节约性能
      if (!store.state.user.userPro) {
        await store.dispatch('user/yhjbxx')
        next(to)
        console.log(to, router)
      }
      next()
    }
  } else {
    if (AAA.includes(to.path.toLowerCase())) {
      next()
    } else {
      Message.success('请登录')

      next('login')
      console.log(token, '333')
    }
  }
})

router.afterEach((to, from, next) => {
  NProgress.done()
})
